//
//  CMResource.m
//  CocoaMesh
//
//  Created by George  Armah on 5/4/09.
//  Copyright 2009 Lafayette College. All rights reserved.
//

#import "CMResource.h"


@implementation CMResource

@synthesize resourceData;

-(id)initWithDictionary:(NSDictionary *)resource 
{
	if ( self = [super init] )
	{
		NSString * key;
		resourceData = [[NSMutableDictionary alloc] init];
		for (key in resource)
		{
			[self setValue:[resource valueForKey:key] forKey:key];
		}
	}
	return self;
}


-(id)initWithResource:(CMResource *)resource
{
	return [self initWithDictionary:[resource convertToCollection]];
}



-(void) dealloc 
{
	[resourceData release];
	[super dealloc];
}


-(void)setValue:(id)value forUndefinedKey:(NSString *)key
{
	[self.resourceData setValue:value forKey:key];
}

- (id)valueForUndefinedKey:(NSString *)key
{
	return [self.resourceData valueForKey:key];
}

//Caller of this method is responsible for retaining dictionary
-(id) convertToCollection
{
	unsigned int outCount, i;
	objc_property_t *properties = class_copyPropertyList([self class], &outCount);
	NSMutableDictionary * dict = [[[NSMutableDictionary alloc] initWithCapacity:outCount] autorelease];
	
	//Add properties except resourceData
	for (i = 0; i < outCount; i++)
	{
		objc_property_t property = properties[i];
		const char * propName = property_getName(property);
		if( propName )
		{
			NSString * propertyName = [NSString stringWithUTF8String:propName];
			if ( ! [propertyName isEqualToString:RESOURCEDATA] )
			{
				[dict setValue:[self valueForKey:propertyName] forKey:propertyName];
			}
		}
	}
	
	//Add everything contained in resourceData
	for (NSString * key in self.resourceData)
	{
		[dict setValue:[self.resourceData valueForKey:key] forKey:key];
	}
	
	free(properties);
	return dict;
}

-(void)populateProperties:(NSDictionary*)propertiesDict
{
	for (id key in propertiesDict)
	{
		[self setValue:[propertiesDict valueForKey:key] forKey:(NSString*)key];
	}
}


-(NSString*)description
{
	return [[self convertToCollection] description];
}

-(BOOL)isEqualTo:(CMResource*)otherResource
{
	return [[self valueForKey:IDKEY] isEqualTo:[otherResource valueForKey:IDKEY]];
}

-(NSUInteger)hash
{
	return [[self valueForKey:IDKEY] hash];
}
@end
